/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.pay.rest;

import cn.hsaf.common.utils.SecurityUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.pay.domain.JjzhWxPayOrders;
import me.zhengjie.pay.service.JjzhWxPayOrdersService;
import me.zhengjie.pay.service.dto.JjzhWxPayOrdersQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author xxx
* @date 2025-03-28
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "居家照护微信支付订单管理")
@RequestMapping("/api/jjzhWxPayOrders")
public class JjzhWxPayOrdersController {
    private static final Logger logger = LoggerFactory.getLogger(WxRefundController.class);
    private final JjzhWxPayOrdersService jjzhWxPayOrdersService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('jjzhWxPayOrders:list')")
    public void exportJjzhWxPayOrders(HttpServletResponse response, JjzhWxPayOrdersQueryCriteria criteria) throws IOException {
        jjzhWxPayOrdersService.download(jjzhWxPayOrdersService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询居家照护微信支付订单")
    @ApiOperation("查询居家照护微信支付订单")
    @PreAuthorize("@el.check('jjzhWxPayOrders:list')")
    public ResponseEntity<Object> queryJjzhWxPayOrders(JjzhWxPayOrdersQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(jjzhWxPayOrdersService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增居家照护微信支付订单")
    @ApiOperation("新增居家照护微信支付订单")
    @PreAuthorize("@el.check('jjzhWxPayOrders:add')")
    public ResponseEntity<Object> createJjzhWxPayOrders(@Validated @RequestBody JjzhWxPayOrders resources){
        return new ResponseEntity<>(jjzhWxPayOrdersService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改居家照护微信支付订单")
    @ApiOperation("修改居家照护微信支付订单")
    @PreAuthorize("@el.check('jjzhWxPayOrders:edit')")
    public ResponseEntity<Object> updateJjzhWxPayOrders(@Validated @RequestBody JjzhWxPayOrders resources){
        jjzhWxPayOrdersService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除居家照护微信支付订单")
    @ApiOperation("删除居家照护微信支付订单")
    @PreAuthorize("@el.check('jjzhWxPayOrders:del')")
    public ResponseEntity<Object> deleteJjzhWxPayOrders(@RequestBody String[] ids) {
        jjzhWxPayOrdersService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @GetMapping("/updateOrdersStatus")
    @Log("更新订单状态")
    @ApiOperation("更新订单状态")
    public ResponseEntity<Object> updateOrdersStatus(HttpServletRequest request) {
        // 获取请求中的订单号和新订单状态
        String orderNo = request.getParameter("orderNo");  // 订单号
        Long status = Long.valueOf(request.getParameter("status"));  // 新的订单状态（通过请求参数传入）

        // 获取当前登录用户的用户名
        String username = SecurityUtils.getCurrentUser().getUsername();

        // 查找数据库中对应的订单信息
        JjzhWxPayOrders order = jjzhWxPayOrdersService.findByOrderNo(orderNo);

        // 如果订单不存在，日志记录并抛出异常
        if (order == null) {
            logger.error("无法找到订单，订单号：{}", orderNo);
            throw new RuntimeException("订单不存在");
        }

        // 记录更新操作的日志，包含变更前后状态信息
        logger.info("{} 更新居家照护订单状态，订单号：{}，变更前状态：{}，变更后状态：{}",
                username, orderNo, order.getStatus(), status);

        // 设置备注说明，表示状态是后台系统更新的
        order.setRemarks("后台系统更新订单状态");

        // 更新订单状态
        order.setStatus(status);

        // 更新数据库中的订单信息
        jjzhWxPayOrdersService.update(order);
        logger.info("订单号：{} 的状态已成功更新为：{}，备注：{}", orderNo, status, order.getRemarks());
        // 返回响应，表示更新操作已成功完成
        return new ResponseEntity<>(HttpStatus.OK);
    }


}
